/**
 * 
 */
package z.tool.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author auzll@163.com
 */
public class InputStreamLoader {
    private static final Log LOG = LogFactory.getLog(InputStreamLoader.class);
    private static ClassLoader systemClassLoader = null;
    
    static {
        try {
            systemClassLoader = ClassLoader.getSystemClassLoader();
        } catch (Exception e) {
        }
    }
    
    public static ClassLoader[] getClassLoaders() {
        return new ClassLoader[] { systemClassLoader,
                Thread.currentThread().getContextClassLoader(),
                PropertiesLoader.class.getClassLoader() };
    }
    
    public static URL getResource(String name) {
        ClassLoader[] classLoaders = getClassLoaders();
        URL url = null;
        
        for (ClassLoader loader : classLoaders) {
            if (null != loader) {
                url = loader.getResource(name);
                if (null == url) {
                    url = loader.getResource("/" + name);
                }
                if (null != url) {
                    break;
                }
            }
        }
        
        if (null == url) {
            try {
                url = new URL(name);
            } catch (Exception e) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("method:getResource", e);
                }
            }
        }
        
        return url;
    }
    
    public static InputStream loadInputStream(String fileName) {
        InputStream is = null;
        
        ClassLoader[] classLoaders = getClassLoaders();
        for (ClassLoader loader : classLoaders) {
            if (null != loader) {
                is = loader.getResourceAsStream(fileName);
                if (null == is) {
                    is = loader.getResourceAsStream("/" + fileName);
                }
                if (null != is) {
                    break;
                }
            }
        }
        
        if (null == is) {
            try {
                is = new FileInputStream(fileName);
            } catch (Exception e) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("method:loadInputStream", e);
                }
            }
        }
        
        return is;
    }
}
